package dao

import (
	"context"
	"forum/app/comment/internal/repository/db/model"
	pb "forum/idl/pb/comment"
	"forum/pkg/util/logger"
	"gorm.io/gorm"
)

type CommentDao struct {
	*gorm.DB
}

func NewCommentDao(ctx context.Context) *CommentDao {
	return &CommentDao{NewDBClient(ctx)}
}

// CreateComment 创建评论
func (dao *CommentDao) CreateComment(req *pb.CommentRequest) (err error) {
	t := &model.Comment{
		UserID:  uint(req.UserID),
		PostID:  uint(req.PostID),
		Content: req.Content,
	}
	if err = dao.DB.Model(&model.Comment{}).Create(&t).Error; err != nil {
		logger.LoggersObj.Error("Comment Create Error:" + err.Error())
		return
	}
	return
}

// UpdateComment 更新评论
func (dao *CommentDao) UpdateComment(req *pb.CommentRequest) (err error) {
	t := &model.Comment{
		UserID:  uint(req.UserID),
		PostID:  uint(req.PostID),
		Content: req.Content,
	}
	if err = dao.DB.Model(&model.Comment{}).Where("user_id = ? AND post_id = ? AND id = ?", req.UserID, req.PostID, req.CommentID).Updates(&t).Error; err != nil {
		logger.LoggersObj.Error("Comment Update Error:" + err.Error())
		return
	}
	return
}

// DeleteComment 删除评论
func (dao *CommentDao) DeleteComment(req *pb.CommentRequest) (err error) {
	if err = dao.DB.Model(&model.Comment{}).Where("user_id = ? AND post_id = ? AND id = ?", req.UserID, req.PostID, req.CommentID).Delete(&model.Comment{}).Error; err != nil {
		logger.LoggersObj.Error("Comment Delete Error:" + err.Error())
		return
	}
	return
}

// ListComment 获取帖子所有评论
func (dao *CommentDao) ListComment(req *pb.CommentRequest) (resp []*model.Comment, err error) {
	err = dao.DB.Model(&model.Comment{}).Where("post_id = ?", req.PostID).
		Offset(int((req.Page - 1) * req.PageSize)).
		Limit(int(req.PageSize)).
		Order("created_at desc").
		Find(&resp).Error
	return
}

// ListCommentByUserID 获取用户的所有评论
func (dao *CommentDao) ListCommentByUserID(req *pb.CommentRequest) (resp []*model.Comment, err error) {
	err = dao.DB.Model(&model.Comment{}).Where("user_id = ?", req.UserID).
		Offset(int((req.Page - 1) * req.PageSize)).
		Limit(int(req.PageSize)).
		Order("created_at desc").
		Find(&resp).Error
	return
}
